/*******************************************************************************
 * Copyright (c) 2009 Dop Sun.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Dop Sun - initial API and implementation
 ******************************************************************************/
package com.softao.ming.gde.internal.core.export;

import org.eclipse.ant.core.AntRunner;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;

import com.softao.ming.gde.internal.core.bootstrap.BootstrapGenerator;
import com.softao.ming.gde.internal.core.bootstrap.BootstrapGeneratorArgs;

/**
 * Do the actual export a GWT Module.
 */
public class GdeApplicationExportOperation implements IWorkspaceRunnable {

	private final GdeApplicationExportInfo mExportInfo;
	
	/**
	 * @param info 
	 */
	public GdeApplicationExportOperation(GdeApplicationExportInfo info) {
		mExportInfo = info;
	}
	
	@Override
	public void run(IProgressMonitor monitor) throws CoreException {
		BootstrapGeneratorArgs args = createBootstrapApplication(monitor);
		
		PluginExporter exporter = new PluginExporter();
		exporter.export(args.getLocation() + "/temp", monitor);

		AntFileGenerator antFileGenerator = new AntFileGenerator();
		IPath antFilePath = antFileGenerator.generate(mExportInfo, args, monitor);
		if (antFilePath == null) {
			return;
		}
		runAntScript(antFilePath);
		
	}
	
	private BootstrapGeneratorArgs createBootstrapApplication(IProgressMonitor monitor) {
		IPath path = new Path(mExportInfo.getOutputLocation());
		
		BootstrapGeneratorArgs args = new BootstrapGeneratorArgs();
		args.setLocation(path.toOSString());
		args.setUseProduct(mExportInfo.isUseProduct());
		if (mExportInfo.isUseProduct()) {
			args.setTargetId(mExportInfo.getProductId());
		} else {
			args.setTargetId(mExportInfo.getApplicationId());
		}
		
		BootstrapGenerator generator = new BootstrapGenerator();
		generator.generate(args, monitor);
		
		return args;
	}

	private void runAntScript(IPath antScriptPath) {
		AntRunner antRunner = new AntRunner();
		antRunner.setBuildFileLocation(antScriptPath.toOSString());
		try {
			antRunner.run();
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
}
